<template>
  <div class="stop-time-dialog">
    <basic-dialog :visible="show"
                  minWidth="1040px"
                  :title="`${statusList[1].label}时间明细`"
                  :isShowClose="true"
                  :isFullScreen="true"
                  @close="$emit('close')">
      <div class="page-content padding-20" style="padding-bottom: 0">
        <div class="form-inline bottom"
                 style="justify-content: space-between;padding: 0">
              <div class="left box">
                <div style="max-width: 1600px; height: 100%">
                  <div class="flex">
                    <select-tooltip v-model="queryParams.shift"
                                    :multiple='false'
                                    :options="shiftOptions"
                                    v-if="scheduling.length !== 0"
                                    msg="加工班次"></select-tooltip>
                    <select-tooltip v-model="queryParams.stopTypeIds"
                                    :multiple='true'
                                    :options="equipmentTypeOptions"
                                    :msg="`${statusList[1].label}类型`"></select-tooltip>
                    <fuzzy-search
                      v-model="queryParams.stopPerson"
                      :title="`${statusList[1].label}人`"
                      :fuzzyObj="['nickName', 'userId']"
                      :is-show-value="false"
                      :fuzzyFunc="fuzzyFunc"
                      isFilter
                      class="margin-r-20"
                    ></fuzzy-search>
                    <div class="q-mr-md flex q-mb-sm margin-b-20">
                      <div class="for-time fontSize-14" style="margin-left: 0px">时长范围(分钟):</div>
                      <q-input outlined
                               class="btn-time"
                               dense
                               mask="#######"
                               v-model="queryParams.stopDurationStart" />
                      <div class="for-time">~</div>
                      <q-input outlined
                               class="btn-time"
                               dense
                               mask="#######"
                               v-model="queryParams.stopDurationEnd" />
                    </div>
                  </div>
                </div>
              </div>
              <div style="display: flex">
                <q-btn class="btn margin-r-10"
                       outline
                       color="primary"
                       @click="resetSearch"
                       label="重置" />
                <q-btn class="btn"
                       unelevated
                       type="submit"
                       color="primary"
                       label="查询"
                       @click="onSubmit" />
              </div>
            </div>
        <div class="form-inline bottom"
             style="justify-content: space-between;padding: 0px 0px 20px 0px">
          <div class="left box">
            <q-btn class="btn margin-r-10"
                   outline
                   color="primary"
                   :disable="!selectedReport.length"
                   @click="onEditMup">
              批量修改
            </q-btn>
          </div>
    </div>
      </div>
      <div class="page-content padding-20" style="padding-top: 0;padding-bottom: 0">
        <q-table
          class="users-table scroll my-sticky-virt scroll-table stick-last-col myTable"
          :columns="tableColumns"
          :data="tableData"
          row-key="timeStamp"
          :loading="loading"
          selection="multiple"
          :selected.sync="selectedReport"
          :pagination.sync="pagination"
          color="primary"
          :hide-bottom="tableData.length != 0"
          style="height: 400px;max-height: 400px;margin: 0 0 20px"
        >
          <template v-slot:body-cell-productName="props">
            <q-td>
              {{props.row.productName || '-'}}
            </q-td>
          </template>
          <template v-slot:body-cell-stopType="props">
            <q-td>
              {{props.row.stopType || '—'}}
            </q-td>
          </template>
          <template v-slot:body-cell-stopCause="props">
            <q-td>
              {{props.row.stopCause || '—'}}
            </q-td>
          </template>
          <template v-slot:body-cell-stopPerson="props">
            <q-td>
              {{props.row.stopPerson || '—'}}
            </q-td>
          </template>
          <template v-slot:body-cell-remark="props">
            <q-td>
              {{props.row.remark || '—'}}
            </q-td>
          </template>
          <template v-slot:body-cell-causeUpdateName="props">
            <q-td>
              {{props.row.causeUpdateName || '—'}}
            </q-td>
          </template>
          <template v-slot:body-cell-btn="props">
            <q-td>
              <q-btn flat color="primary" label="修改原因" class="table-flat-btn" @click="showEditDialog(props.row)"/>
            </q-td>
          </template>
        </q-table>
        <yz-pagination v-model="pagination" @onSearch="getList"/>
      </div>
      <!-- 异常明细 -->
      <edit-detail
        :show="editDetail.show"
        :data="editDetail.data"
        ref="editDetail"
        :isReports="isReports"
        :selectedReport="editDetail.selReport"
        :isFilter="true"
        @getList="getList()"
        @close="editDetail.show = false; selectedReport = []"
        @fillIn="$emit('fillIn')"
      />
    </basic-dialog>
  </div>
</template>

<script>
import { getDowntimeList, getUserName } from '../../../boot/status-monitor/machine'

import editDetail from './edit-detail'
import { date } from 'quasar'
import { getCauseTypeList } from '../../../boot/system/reason'
import _ from 'lodash'
import { mapGetters } from 'vuex'
export default {
  name: 'stop-time-dialog',
  components: {
    editDetail
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    deviceId: {
      default: '',
      required: true
    },
    since: {
      default: '',
      required: true
    },
    before: {
      default: '',
      required: true
    },
    scheduling: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    ...mapGetters(['statusList']),
    shiftOptions () {
      const options = this.scheduling.map(item => ({
        label: item.name,
        value: item.name
      }))
      options.unshift({
        label: '全部',
        value: 'all'
      })
      return options
    },
    tableColumns () {
      return [
        { name: 'startTime', field: 'startTime', label: `${this.statusList[1].label}开始时间`, align: 'left' },
        { name: 'endTime', field: 'endTime', label: `${this.statusList[1].label}结束时间`, align: 'left' },
        { name: 'productName', field: 'productName', label: '作业', align: 'left' },
        { name: 'stopPerson', field: 'stopPerson', label: `${this.statusList[1].label}人`, align: 'left' },
        { name: 'stopType', field: 'stopType', label: `${this.statusList[1].label}类型`, align: 'left' },
        { name: 'stopCause', field: 'stopCause', label: `${this.statusList[1].label}原因`, align: 'left' },
        { name: 'duration', field: 'duration', label: `${this.statusList[1].label}时长`, align: 'left' },
        { name: 'remark', field: 'remark', label: '备注', align: 'left' },
        { name: 'causeUpdateName', field: 'causeUpdateName', label: '原因修改人', align: 'left' },
        { name: 'btn', field: 'btn', label: '操作', align: 'left' }
      ]
    }
  },
  data () {
    return {
      fuzzyFunc: getUserName,
      isReports: false,
      loading: false,
      selectedReport: [],
      materialNameOptions: [],
      queryParams: {
        stopDurationStart: null,
        stopDurationEnd: null,
        stopTypeIds: [],
        stopPerson: null,
        shift: 'all'
      },
      // 表格不分页
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      equipmentTypeOptions: [],
      searchCondition: [{ id: 'materialsNum', name: '停机人' }],
      tableData: [],
      editDetail: {
        show: false,
        data: null
      }
    }
  },
  methods: {
    onSubmit () {
      this.getList()
    },
    onEditMup () {
      // 批量填报不超过60条
      if (this.selectedReport.length > 60) {
        this.$message.warning('批量填报不超过60条')
        return
      }
      this.isReports = true
      this.editDetail.show = true
      this.editDetail.data = this.selectedReport[0]
      this.editDetail.selReport = this.selectedReport
    },
    // 重置
    resetSearch () {
      this.queryParams = {
        shift: 'all',
        stopTypeIds: ['all'],
        stopDurationStart: null,
        stopDurationEnd: null,
        stopPerson: null
      }
    },
    // 获取原因类型列表
    getStopcauseList () {
      return getCauseTypeList(3, true).then(res => {
        if (res.data.length > 0) {
          this.equipmentTypeOptions = [{ label: '全部', id: 'all' }, { label: '空', id: '-1' }, ...res.data]
          this.equipmentTypeOptions.map(v => {
            const item = v
            item.value = v.id
            item.label = v.label
            return item
          })
          this.queryParams.stopTypeIds[0] = 'all'
        }
      })
    },
    showEditDialog (data) {
      this.isReports = false
      this.editDetail.data = { ...data, deviceId: this.deviceId }
      this.editDetail.show = true
    },
    // 获取列表数据
    getList () {
      this.tableData = []
      if (this.deviceId) {
        const params = {
          ...this.pagination,
          deviceId: this.deviceId,
          stopDurationStart: this.queryParams.stopDurationStart,
          stopDurationEnd: this.queryParams.stopDurationEnd,
          stopTypeIds: this.queryParams.stopTypeIds,
          stopPerson: this.queryParams.stopPerson
        }
        if (this.queryParams.shift === 'all') {
          params.end = this.before
          params.since = this.since
        } else {
          const shiftInfo = this.scheduling.find(item => item.name === this.queryParams.shift)
          params.end = shiftInfo.to
          params.since = shiftInfo.from
        }
        if (this.isLtTime(this.queryParams.stopDurationStart, this.queryParams.stopDurationEnd)) return
        params.stopDurationStart = _.isEmpty(this.queryParams.stopDurationStart) ? this.queryParams.stopDurationStart : this.queryParams.stopDurationStart * 60
        params.stopDurationEnd = _.isEmpty(this.queryParams.stopDurationEnd) ? this.queryParams.stopDurationEnd : this.queryParams.stopDurationEnd * 60
        params.stopTypeIds = this.queryParams.stopTypeIds[0] === 'all' || _.isEmpty(this.queryParams.stopTypeIds) ? null : params.stopTypeIds
        if (_.isNil(params.since) || _.isNil(params.end)) return
        this.loading = true
        getDowntimeList(params).then(res => {
          if (res.data && res.data.list) {
            res.data.list.forEach(o => {
              o.startTime = o.startTime && date.formatDate(new Date(o.startTime), 'YYYY-MM-DD HH:mm:ss')
              o.endTime = o.endTime && date.formatDate(new Date(o.endTime), 'YYYY-MM-DD HH:mm:ss')
              o.duration = o.duration === '0秒' ? '不足1秒' : o.duration
            })
            this.tableData = res.data.list
            this.pagination.rowsNumber = res.data.total
          }
        }).finally(() => {
          this.loading = false
          this.$emit('getDetailedCount')
        })
      } else {
        this.tableData = []
      }
    },
    isLtTime (lt, ls) {
      if (!_.isNil(lt) && !_.isNil(ls) && Number(lt) > Number(ls)) {
        this._Message('开始时长不得大于结束时长', () => {})
        return true
      }
      return false
    },
    _Message (msg, fn) {
      return this.$q
        .dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>${msg}</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        }).onOk(fn)
    }
  },
  watch: {
    show: function (newVal) {
      // console.log(newVal)
      if (newVal) {
        this.queryParams = {
          stopTypeIds: ['all'],
          stopDurationStart: null,
          stopDurationEnd: null,
          stopPerson: null,
          shift: 'all'
        }
        this.getList()
      }
    }
  },
  mounted () {
    this.getStopcauseList()
  }
}
</script>

<style scoped lang="scss">
    .for-time {
      line-height: 32px;
      height: 32px;
      text-align: center;
      margin: 0px 6px;
    }
    .btn-time {
      height: 32px;
      max-width: 42px;
    }
    .fontSize-16{
      font-size:16px;
      font-family:PingFang SC;
      font-weight:500;
      color:rgba(51,51,51,1);
    }
</style>
